/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { addMixedIn, getMixInDetail } from '@/services/setup';
import MixInModalItem from './MixInModalItem';
import SmsModal from './SmsModal';
import { findDuplicates } from './utils';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

/**
 * 混合入库，添加修改弹窗
 *  */
const MixInModal = props => {
  const { visible, form, onOk, onCancel, cm_id } = props;

  const [submitting, setSubmitting] = useState(false);
  const [modalConfig, setModalConfig] = useState([]);
  const [commonBrands, setCommonBrands] = useState([]);
  const [originalBrands, setOriginalBrands] = useState({});
  // 需要短信验证的手机号
  const [smsPhone, setSmsPhone] = useState({
    phone: '',
    platform: '',
    password: '',
  });

  const { getFieldDecorator, validateFields, isFieldsTouched, resetFields, setFieldsValue } = form;

  const handleOk = ({ smsCode } = {}) => {
    if (!isFieldsTouched()) {
      onCancel();
      return;
    }
    validateFields((err, values) => {
      if (err) return;
      const params = {
        cm_id,
      };
      const selectBrands = [];
      const data = [];
      Object.keys(values).forEach(key => {
        if (typeof values[key] == 'string') {
          params[key] = values[key];
          return;
        }
        const { checked, platform, username, password, platform_brand } = values[key] || {};
        checked && selectBrands.push(...platform_brand);
        data.push({
          platform,
          username,
          password,
          status: checked ? 1 : 0,
          smsCode: smsCode && smsPhone.platform == platform ? smsCode : '',
          platform_brand,
        });
      });
      params.data = JSON.stringify(data);
      if (cm_id) {
        delete params.phone;
      }
      const duplicates = findDuplicates(selectBrands);
      if (duplicates.length > 0) {
        const msg = duplicates.map(v => originalBrands[v]).join('、');
        message.error(`${msg}所选品牌有重合，请修改`);
        return;
      }

      setSubmitting(true);
      addMixedIn(params)
        .then(res => {
          const { code, msg, data: resData = {} } = res;
          setSubmitting(false);
          if (code == 0) {
            message.success(res.msg);
            setSmsPhone({});
            onOk();
            onCancel();
          } else if (code == '19999' && resData.sms_code) {
            const { username, password } = data.find(v => v.platform == resData.sms_code) || {};
            setSmsPhone({
              phone: username,
              platform: resData.sms_code,
              password,
            });
          } else {
            message.error(msg);
          }
        })
        .catch(() => {
          setSubmitting(false);
        });
    });
  };

  useEffect(
    () => {
      if (visible) {
        getMixInDetail({ cm_id }).then(res => {
          const { phone, info, platform_brand = [], brands } = res;
          setFieldsValue({
            phone,
          });
          setModalConfig(info);
          setCommonBrands(platform_brand);
          setOriginalBrands(brands);
        });
      } else {
        setModalConfig([]);
        resetFields();
      }
    },
    [cm_id, visible],
  );

  const validator = (rule, value, callback) => {
    const { checked, username, password, platform_brand } = value;

    if (checked) {
      if (!username) {
        return callback('请输入对应的账号');
      }
      if (!password) {
        return callback('请输入对应的密码');
      }
      if (platform_brand.length == 0) {
        return callback('请选择对应的品牌');
      }
    }
    return callback();
  };

  return (
    <Modal
      centered
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      confirmLoading={submitting}
      okText="保存"
      width={750}
    >
      <Form {...formItemLayout}>
        <FormItem label="驿站账号">
          {getFieldDecorator('phone', {
            rules: [
              {
                required: true,
                message: '请输入驿站手机号',
              },
            ],
          })(
            <Input
              disabled={!!cm_id}
              allowClear
              placeholder="请输入驿站手机号"
              style={{ width: 250 }}
            />,
          )}
        </FormItem>
        {modalConfig.map(item => (
          <FormItem key={item.platform} wrapperCol={{ span: 24 }}>
            {getFieldDecorator(item.platform, {
              initialValue: item,
              rules: [{ validator }],
            })(<MixInModalItem commonBrands={commonBrands} />)}
          </FormItem>
        ))}
      </Form>
      <SmsModal
        submitting={submitting}
        phone={smsPhone.phone}
        platform={smsPhone.platform}
        password={smsPhone.password}
        onOk={handleOk}
        onCancel={() => {
          setSmsPhone({});
        }}
      />
    </Modal>
  );
};

export default Form.create()(MixInModal);
